#!/bin/bash

DIR_BIN=$(cd `dirname $0`; pwd)
USER=$(whoami)
cpplint_tmpfile="/tmp/.$USER.svn.cpplint.$$"
ci_tmpfile="/tmp/.$USER.svn.ci.$$"

function EXIT() {
  rm -f $ci_tmpfile
  rm -f $cpplint_tmpfile
  if [[ $# -ne 0 ]]; then
    echo $*
  fi
  exit
}

function cpplint() {
  tmpfile=$cpplint_tmpfile
  python tools/cpplint.py $1 > $tmpfile 2>&1
  errorinfo=$(grep 'Total errors found' $tmpfile)
  errorline=$(echo $errorinfo | wc -l)
  errors=$(echo $errorinfo | awk '{print $4}')
  if [[ $errors -ne 0 || $errorline -eq 0 ]]; then
    cat $tmpfile
    return 1
  fi
  return 0
}

# ci all files that can be
if [[ $# -eq 0 ]]; then
  tmpfile=$ci_tmpfile
  clname="wstc_cl_$(date '+%Y_%m_%d_%H')"
  clok=0
  svn st > $tmpfile
  while read op file
  do
    if [[ ! -f $file ]]; then
      if [[ $op != 'D' ]]; then
        continue
      fi
    fi
    if [[ $file == '.sconsign.dblite' ]]; then
      continue
    fi
    cpplint $file
    ret=$?
    if [[ $ret -ne 0 ]]; then
      clok=$ret
    fi
    if [[ $op == '?' ]]; then
      svn add $file
    fi
    svn cl $clname $file
  done < $tmpfile
  if [[ $clok -ne 0 ]]; then
    EXIT "ERRORS FOUND IN CL=$clname"
  fi
  cl=$(svn st | grep $clname | wc -l)
  if [[ $cl -eq 0 ]]; then
    echo 'NO NEED CI FILES!'
    EXIT
  fi

  echo "-----------------------SVN ST--------------------"
  svn st
  echo "-------------------------------------------------"
  echo ""

  read -p "svn ci $clname ?(yes/no)" yes

  if [[ $yes == 'y' || $yes == 'yes' ]]; then
    echo "svn ci --changelist=$clname ..."
    svn ci --changelist=$clname -m $clname
  fi
  EXIT
fi

case $1 in
  'install')
    home_bin="$HOME/bin"
    if [[ ! -d $home_bin ]]; then
      mkdir -p $home_bin
    fi
    ln -sf "$DIR_BIN/svnx" $home_bin
    echo "ln -sf $DIR_BIN/svnx $home_bin"
    chmod u+x $home_bin/svnx
    ;;
  'mkdir')
    if [[ $# -ne 2 ]]; then
      echo 'svn mkdir $dirname'
      EXIT
    fi
    svn mkdir $2; svn ci $2 -m "svn_mkdir_$2"
    ;;
  'cpplint' | 'check')
    if [[ $# -ne 2 ]]; then
      echo "svnx check cppfile"
      EXIT
    fi
    cpplint $2
    ;;
  *)
    svn $*
esac
